<template>
	<div class="madp-campaign">
		<basic-container>
			<el-form :inline="true" :model="searchForm" ref="searchForm" class="madp-search-form">
				<el-form-item label="活动名称:">
					<el-input v-model.trim="searchForm.actName" placeholder="请输入活动名称"></el-input>
				</el-form-item>
				<el-form-item label="活动时间:">
					<el-date-picker
						v-model="dateRangeVal"
						type="daterange"
						range-separator="至"
						start-placeholder="开始日期"
						end-placeholder="结束日期"
						format="yyyy-MM-dd"
						value-format="yyyy-MM-dd"
						@change="setStartTimeAndEndTime"
					></el-date-picker>
				</el-form-item>
				<el-form-item label="状态:">
					<el-select v-model="searchForm.actStatus">
						<el-option v-for="item in isRecheck ? checkStatusData : statusData" :key="item.status" :label="item.statusDesc" :value="item.status"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="fetchActivityList">搜索</el-button>
					<el-button plain @click="clearSearchForm">清空</el-button>
				</el-form-item>
			</el-form>

			<div class="madp-btn-group">
				<div v-if="!isRecheck">
					<el-button type="primary" style="margin-right: 10px" @click="showAddBlock()">新增</el-button>
					<el-button type="primary" style="margin-right: 10px" @click="submitCheck">推审</el-button>
				</div>
				<el-button type="primary" style="margin-right: 10px" v-if="isRecheck" @click="checkActivity(null, 'pass')">通过</el-button>
			</div>
			<!-- 活动列表数据 -->
			<div class="madp-campaign-table">
				<el-table
					:header-cell-style="{
						background: 'rgb(255, 191, 191)',
						color: 'rgb(44,44,44)',
					}"
					stripe
					:data="activityData"
					v-loading="actTableLoading"
					@selection-change="handleSelectionChange"
				>
					<el-table-column type="selection" width="55"></el-table-column>
					<el-table-column prop="actName" label="名称" align="center"></el-table-column>
					<el-table-column label="活动封面" align="center">
						<template slot-scope="scope">
							<div class="madp-activity-cover">
								<img :src="scope.row.actCover" />
							</div>
						</template>
					</el-table-column>
					<el-table-column label="开始时间" align="center">
						<template slot-scope="scope">{{ scope.row.startTime.split(' ')[0] }}</template>
					</el-table-column>
					<el-table-column label="结束时间" align="center">
						<template slot-scope="scope">{{ scope.row.endTime.split(' ')[0] }}</template>
					</el-table-column>
					<el-table-column prop="actOrder" label="排序" align="center"></el-table-column>
					<el-table-column prop="actStatusDescribe" label="状态" align="center"></el-table-column>
					<el-table-column label="原因" align="center">
						<template slot-scope="scope">
							{{ scope.row.actStatus === 3 ? scope.row.actReason : '-' }}
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center">
						<template slot-scope="scope">
							<!-- 非审核员身份 -->
							<div v-if="!isRecheck">
								<el-button type="text" :disabled="scope.row.actStatus === 4 ? true : false" @click="showAddBlock(scope.row)">编辑</el-button>
								<el-button type="text" :disabled="scope.row.actStatus === 4 ? true : false" @click="deleteActivity(scope.row)">删除</el-button>
								<el-button v-if="scope.row.actStatus === 2 || scope.row.actStatus === 4 || scope.row.actStatus === 5" type="text" @click="publishOrStopActivity(scope.row)">
									{{ scope.row.actStatus === 4 ? '暂停' : '发布' }}
								</el-button>
							</div>
							<!-- 审核员身份 -->
							<div v-if="isRecheck">
								<!-- <el-button
								type="text"
								
								@click="checkActivity(scope.row, 'pass')"
								>通过</el-button
                                >-->
								<el-button type="text" @click="checkActivity(scope.row, 'reject')">不通过</el-button>
							</div>
						</template>
					</el-table-column>
				</el-table>
			</div>

			<!-- 列表分页 -->
			<el-pagination
				background
				v-if="pagination.total > 0"
				class="madp-black-pagination"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="pagination.current"
				:page-sizes="[10, 20, 30, 50, 100]"
				:page-size="pagination.size"
				layout="total, sizes, prev, pager, next, jumper"
				:total="pagination.total"
			></el-pagination>

			<!-- 新增活动 -->
			<el-dialog :title="dialogTitle" :visible.sync="showAddDialog" @close="closeAddBlock" width="600px" :close-on-click-modal="false">
				<el-form :model="dialogForm" :rules="rules" ref="dialogForm" class="madp-add-form" label-width="100px">
					<el-form-item label="活动名称:" prop="actName">
						<el-input v-model.trim="dialogForm.actName" placeholder="请输入活动名称"></el-input>
					</el-form-item>
					<el-form-item label="封面:" prop="actCover">
						<el-upload
							class="madp-edit-input"
							:headers="headers"
							accept="image/jpg, image/jpeg, image/png, image/gif"
							action="/admin/sys-file/upload"
							:show-file-list="false"
							:on-success="handleAvatarSuccess"
						>
							<img v-if="dialogForm.actCover" :src="dialogForm.actCover" class="madp-edit-avatar" />
							<i v-else class="el-icon-plus madp-edit-avatar-icon"></i>
						</el-upload>
					</el-form-item>
					<el-form-item label="活动链接:" prop="actLink">
						<el-input v-model.trim="dialogForm.actLink" placeholder="请输入链接"></el-input>
					</el-form-item>
					<el-form-item label="排序:" prop="actOrder">
						<el-input type="number" v-model.number="dialogForm.actOrder" placeholder="请输入排序"></el-input>
					</el-form-item>
					<el-form-item label="活动时间:" prop="addDateRangeVal">
						<el-date-picker
							v-model="dialogForm.addDateRangeVal"
							type="daterange"
							range-separator="至"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							format="yyyy-MM-dd"
							value-format="yyyy-MM-dd"
							:picker-options="{
								disabledDate(time) {
									return time.getTime() < Date.now() - 8.64e7;
								},
							}"
							@change="setDialogForm"
						></el-date-picker>
					</el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button :loading="submitLoading" @click="closeAddBlock">取消</el-button>
					<el-button type="primary" :loading="submitLoading" @click="submitDialogForm">确定</el-button>
				</div>
			</el-dialog>
		</basic-container>
	</div>
</template>
<script>
import { activityList, addActivity, updateActivity, deleteActivity, auditStatus } from '@/api/operation-manage/marketing-campaign';
import store from '@/store';
import { mapGetters } from 'vuex';
export default {
	data() {
		let validateLink = (rule, value, callback) => {
			if (!value) {
				return callback(new Error('请输入活动链接'));
			}
		};
		let validateSort = (rule, value, callback) => {
			if (value) {
				//正则
				const patt = /^\d{1,3}$/;
				//检测排序输入
				if (patt.test(value)) {
					callback();
				} else {
					callback(new Error('排序值只能在0到999之间！'));
				}
			} else {
				callback();
			}
		};
		return {
			// 账号角色:是否审核员
			isRecheck: false,
			dateRangeVal: [],
			searchForm: {
				actName: '',
				startTime: '',
				endTime: '',
				actStatus: '',
			},
			statusData: [
				{
					status: 0,
					statusDesc: '推审',
				},
				{
					status: 1,
					statusDesc: '待审核',
				},
				{
					status: 2,
					statusDesc: '通过',
				},
				{
					status: 3,
					statusDesc: '不通过',
				},
				{
					status: 4,
					statusDesc: '发布',
				},
				{
					status: 5,
					statusDesc: '暂停',
				},
			],
			checkStatusData: [
				{
					status: 1,
					statusDesc: '待审核',
				},
				{
					status: 2,
					statusDesc: '通过',
				},
				{
					status: 3,
					statusDesc: '不通过',
				},
			],

			// 新增/编辑活动
			showAddDialog: false,
			dialogTitle: '新增',
			submitLoading: false,
			dialogForm: {
				actName: '',
				actCover: '',
				actLink: '',
				actOrder: 1,
				addDateRangeVal: [],
			},
			rules: {
				actName: [
					{
						required: true,
						message: '请输入活动名称',
						trigger: 'blur',
					},
				],
				actCover: [
					{
						required: true,
						message: '请选择活动封面',
						trigger: 'change',
					},
				],
				actLink: [
					{
						required: true,
						message: '请输入活动链接',
						trigger: 'blur',
					},
				],
				actOrder: [
					{
						required: false,
						message: '请输入排序',
						trigger: 'blur',
						validator: validateSort,
					},
				],
				addDateRangeVal: [
					{
						required: true,
						message: '请选择活动时间',
						trigger: 'change',
					},
				],
			},
			headers: {
				Authorization: 'Bearer ' + store.getters.access_token,
			},
			multipleSelection: [],
			selectActivitiesIds: [],

			// 列表数据
			activityData: [],
			pagination: {
				current: 1,
				size: 10,
			},
		};
	},
	computed: {
		...mapGetters(['roleCodes']),
	},
	created() {
		if (this.roleCodes.indexOf('ROLE_CP_AUDIT') > -1) {
			this.isRecheck = true;
		} else {
			this.isRecheck = false;
		}
		this.fetchActivityList();
	},
	mounted() {},
	methods: {
		// 界面初始化
		fetchActivityList() {
			this.actTableLoading = true;
			let searchFormData = Object.assign(this.searchForm, {
				size: this.pagination.size,
				current: this.pagination.current,
			});
			for (let key in searchFormData) {
				if (searchFormData[key] === '') {
					delete searchFormData[key];
				}
			}
			activityList(searchFormData)
				.then((res) => {
					this.actTableLoading = false;
					if (res.data && res.data.code === 0) {
						let data = res.data.data;
						this.activityData = data.records;
						let { current, size, pages, total } = data;
						this.pagination = { current, size, pages, total };
					}
				})
				.catch(() => {
					this.actTableLoading = false;
				});
		},
		setStartTimeAndEndTime(val) {
			if (val) {
				let startTime = val[0];
				let endTime = val[1];
				this.searchForm.startTime = startTime;
				this.searchForm.endTime = endTime;
			}
		},
		clearSearchForm() {
			this.dateRangeVal = [];
			this.searchForm = {
				actName: '',
				startTime: '',
				endTime: '',
				actStatus: '',
			};
			this.fetchActivityList();
		},

		/**
		 * 列表数据相关操作 新增、编辑活动
		 * 新增、编辑 showAddBlock closeAddBlock
		 * 活动时间范围 setDialogForm
		 * 上传封面  handleAvatarSuccess
		 * 推审操作  submitCheck
		 * 删除活动 deleteActivity
		 * 审核活动 checkActivity,
		 * 更改活动状态 auditActivityStatus
		 */
		showAddBlock(data) {
			this.showAddDialog = true;
			if (data) {
				this.dialogTitle = '编辑';
				this.$nextTick(() => {
					let obj = JSON.parse(JSON.stringify(data));
					obj.addDateRangeVal = [new Date(obj.startTime), new Date(obj.endTime)];
					this.dialogForm = obj;
				});
			} else {
				this.dialogTitle = '新增';
				this.dialogForm = {
					actName: '',
					actCover: '',
					actLink: '',
					actOrder: 1,
					addDateRangeVal: [],
				};
			}
		},
		closeAddBlock() {
			this.showAddDialog = false;
			this.dialogForm = {
				actName: '',
				actCover: '',
				actLink: '',
				actOrder: 1,
				addDateRangeVal: [],
			};
			this.$refs.dialogForm.resetFields();
		},
		setDialogForm(val) {
			if (val) {
				let startTime = val[0];
				let endTime = val[1];
				this.dialogForm.startTime = startTime;
				this.dialogForm.endTime = endTime;
			}
		},
		handleAvatarSuccess(res) {
			if (res.code === 0) {
				this.dialogForm.actCover = res.data.url;
				this.$forceUpdate();
				this.$refs.dialogForm.clearValidate('actCover');
			}
		},
		submitDialogForm() {
			this.$refs.dialogForm.validate((valid) => {
				if (valid) {
					if (this.dialogForm['id']) {
						let { id, actName, actCover, actLink, actOrder, startTime, endTime } = this.dialogForm;
						startTime = startTime.split(' ')[0];
						endTime = endTime.split(' ')[0];
						let obj = {
							id,
							actName,
							actCover,
							actLink,
							actOrder,
							startTime,
							endTime,
						};
						updateActivity(obj).then((res) => {
							if (res.data && res.data.code === 0) {
								this.$message.success('该活动编辑成功！');
								this.closeAddBlock();
								this.fetchActivityList();
							}
						});
					} else {
						let { actName, actCover, actLink, actOrder, startTime, endTime } = this.dialogForm;
						let obj = {
							actName,
							actCover,
							actLink,
							actOrder,
							startTime,
							endTime,
						};
						addActivity(obj).then((res) => {
							if (res.data && res.data.code === 0) {
								this.$message.success('该活动添加成功！');
								this.closeAddBlock();
								this.fetchActivityList();
							}
						});
					}
				} else {
					return false;
				}
			});
		},
		handleSelectionChange(val) {
			this.multipleSelection = val;
			this.selectActivitiesIds = val.map((item) => {
				return item.id;
			});
		},
		submitCheck() {
			if (this.selectActivitiesIds.length === 0) {
				this.$message.error('请先选择要推审的活动！');
				return;
			}
			let obj = {
				ids: this.selectActivitiesIds,
				actStatus: 1,
			};
			this.$confirm('确定提审已选择活动?', '', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					this.auditActivityStatus(obj, () => {
						this.$message.success('已推审！');
					});
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消审核',
					});
				});
		},
		deleteActivity(data) {
			let obj = {
				id: data.id,
			};
			this.$confirm('确定删除该活动?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					deleteActivity(obj).then((res) => {
						if (res.data && res.data.code === 0) {
							this.$message.success('删除成功！');
							this.pagination.current = 1;
							this.fetchActivityList();
						}
					});
				})
				.catch(() => {});
		},
		checkActivity(data, type) {
			if (type === 'pass') {
				if (this.selectActivitiesIds.length === 0) {
					this.$message.error('请先选择要审核通过的活动！');
					return;
				}
				let obj = {
					ids: this.selectActivitiesIds,
					actStatus: 2,
				};
				// 批量通过
				this.$confirm('确定通过已选择活动?', '', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				})
					.then(() => {
						this.auditActivityStatus(obj, () => {
							this.$message.success('审核通过！');
						});
					})
					.catch(() => {
						this.$message({
							type: 'info',
							message: '已取消审核',
						});
					});
			} else {
				this.$prompt('请输入不通过的原因', '', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					inputValidator: (value) => {
						if (!value) return false;
					},
					inputErrorMessage: '请输入不通过的原因',
				})
					.then(({ value }) => {
						let obj = {
							actReason: value,
							ids: [data.id],
							actStatus: 3,
						};
						this.auditActivityStatus(obj, () => {
							this.$message.success('已审核！');
						});
					})
					.catch(() => {
						this.$message({
							type: 'info',
							message: '已取消审核',
						});
					});
			}
		},
		publishOrStopActivity(data) {
			// actStatus: 4 发布 5 暂停
			let { id, actStatus } = data;
			let obj = {
				ids: [id],
				actStatus: actStatus === 4 ? 5 : 4,
			};
			let doStr = actStatus === 4 ? '暂停' : '发布';
			this.$confirm(`确定${doStr}此活动?`, '', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					this.auditActivityStatus(obj, () => {
						let messageStr = actStatus === 4 ? '该活动已暂停' : '该活动已发布';
						this.$message.success(messageStr);
					});
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消该操作',
					});
				});
		},
		auditActivityStatus(obj, callback) {
			auditStatus(obj).then((res) => {
				if (res.data && res.data.code === 0) {
					this.pagination.current = 1;
					this.fetchActivityList();
					callback && callback();
				}
			});
		},

		// 分页
		handleSizeChange(val) {
			this.pagination.size = val;
			this.pagination.current = 1;
			this.fetchActivityList();
		},
		handleCurrentChange(val) {
			this.pagination.current = val;
			this.fetchActivityList();
		},
	},
};
</script>
<style lang="scss" scoped>
/deep/ .el-date-editor .el-range-separator {
	width: 25px !important;
}
/deep/ .el-form.madp-search-form {
	display: flex;
	flex-direction: row;
	justify-content: flex-end;
}
.madp-black-pagination {
	display: flex;
	flex-direction: row;
	justify-content: flex-end;
	margin-top: 10px;
}

// 新增/编辑
.madp-add-form {
	.el-input {
		width: 300px;
	}
	.el-input__inner {
		width: 300px;
	}

	/deep/ .madp-edit-input .el-upload {
		width: 80px;
		height: 80px;
		display: flex;
		align-items: center;
		justify-content: center;
		border: 1px solid #f2f2f2;
		border-radius: 4px;
		margin: 0;
		.madp-edit-avatar-icon {
			font-size: 40px;
			color: #b5b5b5;
		}
	}
	.madp-edit-avatar {
		display: flex;
		align-items: center;
		width: 80px;
		height: 80px;
		object-fit: contain;
		border-radius: 4px;
	}
}
.madp-activity-cover {
	display: flex;
	justify-content: center;
	align-items: center;
	img {
		width: 50px;
		height: 50px;
		object-fit: contain;
	}
}
.madp-campaign-table {
	margin-top: 20px;
}
</style>
